/*
 * Copyright 2010 Alexey Romensky
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

/*
 * User: Alexey Romensky
 * Date: 21.02.2010
 * Time: 22:41:05
 */
package com.googlecode.gwt.logging.api.client.impl;

import com.googlecode.gwt.logging.api.client.LogData;
import org.slf4j.Marker;

import java.util.HashMap;
import java.util.Map;

class Slf4jLogData implements LogData {

    private static final char DELIM_START = '{';

    private static final String DELIM_STR = "{}";

    private static final char ESCAPE_CHAR = '\\';

    private final String callerFileName;

    private final Marker marker;

    private final String format;

    private final Object[] arguments;

    private final Throwable throwable;

    private String message;

    public Slf4jLogData(Marker marker, String format, Object[] arguments, Throwable throwable, String callerFileName) {
        this.marker = marker;
        this.format = format;
        this.arguments = arguments;
        this.throwable = throwable;
        this.callerFileName = callerFileName;
    }

    public Slf4jLogData(String callerFileName, String format) {
        this.callerFileName = callerFileName;
        this.marker = null;
        this.format = format;
        this.arguments = null;
        this.throwable = null;
    }

    public Slf4jLogData(String callerFileName, String format, Throwable throwable) {
        this.callerFileName = callerFileName;
        this.marker = null;
        this.format = format;
        this.arguments = null;
        this.throwable = throwable;
    }

    public Slf4jLogData(String callerFileName, String format, Object[] arguments) {
        this.callerFileName = callerFileName;
        this.marker = null;
        this.format = format;
        this.arguments = arguments;
        this.throwable = null;
    }

    public Slf4jLogData(String format, Object[] arguments, Throwable throwable, String callerFileName) {
        this.callerFileName = callerFileName;
        this.marker = null;
        this.format = format;
        this.arguments = arguments;
        this.throwable = throwable;
    }

    public Slf4jLogData(String callerFileName, Marker marker, String format) {
        this.callerFileName = callerFileName;
        this.marker = marker;
        this.format = format;
        this.arguments = null;
        this.throwable = null;
    }

    public Slf4jLogData(String callerFileName, Marker marker, String format, Throwable throwable) {
        this.callerFileName = callerFileName;
        this.marker = marker;
        this.format = format;
        this.arguments = null;
        this.throwable = throwable;
    }

    public Slf4jLogData(String callerFileName, Marker marker, String format, Object[] arguments) {
        this.callerFileName = callerFileName;
        this.marker = marker;
        this.format = format;
        this.arguments = arguments;
        this.throwable = null;
    }

    public String getCallerFileName() {
        return callerFileName;
    }

    @Override
    public Marker getMarker() {
        return marker;
    }

    @Override
    public String getMessage() {

        if (message == null) {
            message = arrayFormat(format, arguments);
        }

        return message;
    }

    @Override
    public Throwable getThrowable() {
        return throwable;
    }

    /**
     * @param messagePattern The message pattern which will be parsed and formatted
     * @param argArray       An array of arguments to be substituted in place of formatting
     *                       anchors
     * @return The formatted message
     */
    private static String arrayFormat(final String messagePattern, final Object[] argArray) {

        if (messagePattern == null) {
            return null;
        }
        if (argArray == null) {
            return messagePattern;
        }
        int i = 0;
        int j;
        StringBuffer sbuf = new StringBuffer(messagePattern.length() + 50);

        for (int L = 0; L < argArray.length; L++) {

            j = messagePattern.indexOf(DELIM_STR, i);

            if (j == -1) {
                // no more variables
                if (i == 0) { // this is a simple string
                    return messagePattern;
                } else { // add the tail string which contains no variables and return
                    // the result.
                    sbuf.append(messagePattern.substring(i, messagePattern.length()));
                    return sbuf.toString();
                }
            } else {
                if (isEscapedDelimeter(messagePattern, j)) {
                    if (!isDoubleEscaped(messagePattern, j)) {
                        L--; // DELIM_START was escaped, thus should not be incremented
                        sbuf.append(messagePattern.substring(i, j - 1));
                        sbuf.append(DELIM_START);
                        i = j + 1;
                    } else {
                        // The escape character preceding the delimiter start is
                        // itself escaped: "abc x:\\{}"
                        // we have to consume one backward slash
                        sbuf.append(messagePattern.substring(i, j - 1));
                        deeplyAppendParameter(sbuf, argArray[L], new HashMap<Object, Object>());
                        i = j + 2;
                    }
                } else {
                    // normal case
                    sbuf.append(messagePattern.substring(i, j));
                    deeplyAppendParameter(sbuf, argArray[L], new HashMap<Object, Object>());
                    i = j + 2;
                }
            }
        }
        // append the characters following the last {} pair.
        sbuf.append(messagePattern.substring(i, messagePattern.length()));
        return sbuf.toString();
    }

    private static boolean isEscapedDelimeter(String messagePattern, int delimeterStartIndex) {

        if (delimeterStartIndex == 0) {
            return false;
        }
        char potentialEscape = messagePattern.charAt(delimeterStartIndex - 1);
        return potentialEscape == ESCAPE_CHAR;
    }

    private static boolean isDoubleEscaped(String messagePattern, int delimeterStartIndex) {
        return delimeterStartIndex >= 2 && messagePattern.charAt(delimeterStartIndex - 2) == ESCAPE_CHAR;
    }

    // special treatment of array values was suggested by 'lizongbo'

    private static void deeplyAppendParameter(StringBuffer sbuf, Object o, Map<Object, Object> seenMap) {

        if (o == null) {
            sbuf.append("null");
            return;
        }
        if (!o.getClass().isArray()) {
            safeObjectAppend(sbuf, o);
        } else {
            // check for primitive array types because they
            // unfortunately cannot be cast to Object[]
            if (o instanceof boolean[]) {
                booleanArrayAppend(sbuf, (boolean[]) o);
            } else if (o instanceof byte[]) {
                byteArrayAppend(sbuf, (byte[]) o);
            } else if (o instanceof char[]) {
                charArrayAppend(sbuf, (char[]) o);
            } else if (o instanceof short[]) {
                shortArrayAppend(sbuf, (short[]) o);
            } else if (o instanceof int[]) {
                intArrayAppend(sbuf, (int[]) o);
            } else if (o instanceof long[]) {
                longArrayAppend(sbuf, (long[]) o);
            } else if (o instanceof float[]) {
                floatArrayAppend(sbuf, (float[]) o);
            } else if (o instanceof double[]) {
                doubleArrayAppend(sbuf, (double[]) o);
            } else {
                objectArrayAppend(sbuf, (Object[]) o, seenMap);
            }
        }
    }

    private static void safeObjectAppend(StringBuffer sbuf, Object o) {

        try {
            String oAsString = o.toString();
            sbuf.append(oAsString);
        } catch (Throwable t) {
            System.err
                    .println("SLF4J: Failed toString() invocation on an object of type ["
                            + o.getClass().getName() + "]");
            t.printStackTrace();
            sbuf.append("[FAILED toString()]");
        }
    }

    private static void objectArrayAppend(StringBuffer sbuf, Object[] a, Map<Object, Object> seenMap) {

        sbuf.append('[');
        if (!seenMap.containsKey(a)) {
            seenMap.put(a, null);
            final int len = a.length;
            for (int i = 0; i < len; i++) {
                deeplyAppendParameter(sbuf, a[i], seenMap);
                if (i != len - 1)
                    sbuf.append(", ");
            }
            // allow repeats in siblings
            seenMap.remove(a);
        } else {
            sbuf.append("...");
        }
        sbuf.append(']');
    }

    private static void booleanArrayAppend(StringBuffer sbuf, boolean[] a) {

        sbuf.append('[');
        final int len = a.length;
        for (int i = 0; i < len; i++) {
            sbuf.append(a[i]);
            if (i != len - 1)
                sbuf.append(", ");
        }
        sbuf.append(']');
    }

    private static void byteArrayAppend(StringBuffer sbuf, byte[] a) {

        sbuf.append('[');
        final int len = a.length;
        for (int i = 0; i < len; i++) {
            sbuf.append(a[i]);
            if (i != len - 1)
                sbuf.append(", ");
        }
        sbuf.append(']');
    }

    private static void charArrayAppend(StringBuffer sbuf, char[] a) {

        sbuf.append('[');
        final int len = a.length;
        for (int i = 0; i < len; i++) {
            sbuf.append(a[i]);
            if (i != len - 1)
                sbuf.append(", ");
        }
        sbuf.append(']');
    }

    private static void shortArrayAppend(StringBuffer sbuf, short[] a) {

        sbuf.append('[');
        final int len = a.length;
        for (int i = 0; i < len; i++) {
            sbuf.append(a[i]);
            if (i != len - 1)
                sbuf.append(", ");
        }
        sbuf.append(']');
    }

    private static void intArrayAppend(StringBuffer sbuf, int[] a) {

        sbuf.append('[');
        final int len = a.length;
        for (int i = 0; i < len; i++) {
            sbuf.append(a[i]);
            if (i != len - 1)
                sbuf.append(", ");
        }
        sbuf.append(']');
    }

    private static void longArrayAppend(StringBuffer sbuf, long[] a) {

        sbuf.append('[');
        final int len = a.length;
        for (int i = 0; i < len; i++) {
            sbuf.append(a[i]);
            if (i != len - 1)
                sbuf.append(", ");
        }
        sbuf.append(']');
    }

    private static void floatArrayAppend(StringBuffer sbuf, float[] a) {

        sbuf.append('[');
        final int len = a.length;
        for (int i = 0; i < len; i++) {
            sbuf.append(a[i]);
            if (i != len - 1)
                sbuf.append(", ");
        }
        sbuf.append(']');
    }

    private static void doubleArrayAppend(StringBuffer sbuf, double[] a) {

        sbuf.append('[');
        final int len = a.length;
        for (int i = 0; i < len; i++) {
            sbuf.append(a[i]);
            if (i != len - 1)
                sbuf.append(", ");
        }
        sbuf.append(']');
    }
}
